package com.xhj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhj.client.VodClient;
import com.xhj.config.CourseQuery;
import com.xhj.entity.*;
import com.xhj.mapper.CourseMapper;
import com.xhj.service.ChapterService;
import com.xhj.service.CourseDescriptionService;
import com.xhj.service.CourseService;
import com.xhj.service.VideoService;
import com.xhj.util.ResultEntity;
import com.xhj.vo.CourseInfoVo;
import com.xhj.vo.CoursePublishVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseDescriptionService courseDescriptionService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private VodClient vodClient;

    @Override
    public String saveCourse(CourseInfoForm courseInfoForm) {
        Course course = new Course();
        // 设置状态为未发布
        course.setStatus(Course.COURSE_DRAFT);
        BeanUtils.copyProperties(courseInfoForm,course);
        boolean resultSave = this.save(course);
        // 判读是否保存成功
        if (!resultSave) throw new RuntimeException("课程信息保存失败！");
        // 获取保存后课程的courseId
        String courseId = course.getId();
        // 保存CourseDescription
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(courseId);
        courseDescription.setDescription(courseInfoForm.getDescription());
        boolean resultSaveDescription = courseDescriptionService.save(courseDescription);
        if (!resultSaveDescription) throw new RuntimeException("课程描述保存失败！");

        return courseId;
    }

    @Override
    public CourseInfoForm getCourseInfoFormById(String id) {
        Course course = this.getById(id);
        // 判断是否存在该course
        if (course == null) throw new RuntimeException("该课程不存在！");
        // 根据课程Id查询对应CourseDescription
        String courseId = course.getId();
        CourseDescription courseDescription = courseDescriptionService.getById(courseId);
        String description = courseDescription.getDescription();

        CourseInfoForm courseInfoForm = new CourseInfoForm();
        BeanUtils.copyProperties(course,courseInfoForm);

        if (!StringUtils.isEmpty(description)) courseInfoForm.setDescription(description);

        return courseInfoForm;
    }

    @Override
    public void updateCourseById(CourseInfoForm courseInfoForm) {
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm,course);
        boolean resultSave = this.updateById(course);
        // 判读是否保存成功
        if (!resultSave) throw new RuntimeException("课程信息更新失败！");
        // 获取保存后课程的courseId
        String courseId = courseInfoForm.getId();
        // 保存CourseDescription
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(courseId);
        courseDescription.setDescription(courseInfoForm.getDescription());
        boolean resultSaveDescription = courseDescriptionService.updateById(courseDescription);
        if (!resultSaveDescription) throw new RuntimeException("课程描述更新失败！");
    }

    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {

        CoursePublishVo coursePublishVo = baseMapper.selectCoursePublishVoById(id);
        if (coursePublishVo == null) throw new RuntimeException("未查到该课程相关信息");
        return coursePublishVo;
    }

    @Override
    public void publishCourseById(String id) {
        Course course = this.getById(id);
        course.setStatus(Course.COURSE_NORMAL);
        boolean result = this.updateById(course);
        if (!result) throw new RuntimeException("发布课程失败！");
    }

    @Override
    public IPage<Course> getListByCourseQuery(Page<Course> pageParam, CourseQuery courseQuery) {
        if (courseQuery == null) return baseMapper.selectPage(pageParam,null);
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) queryWrapper.eq("subject_id",courseQuery.getSubjectId());
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) queryWrapper.eq("subject_parent_id",courseQuery.getSubjectParentId());
        if (!StringUtils.isEmpty(courseQuery.getTeacherId())) queryWrapper.eq("teacher_id",courseQuery.getTeacherId());
        if (!StringUtils.isEmpty(courseQuery.getTitle())) queryWrapper.like("title",courseQuery.getTitle());
        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) queryWrapper.orderByDesc("gmt_create",courseQuery.getGmtCreateSort());
        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) queryWrapper.orderByDesc("buy_count",courseQuery.getBuyCountSort());
        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) queryWrapper.orderByDesc("price",courseQuery.getPriceSort());
        // 根据条件查询分页数据
        IPage<Course> courseIPage = baseMapper.selectPage(pageParam, queryWrapper);
        if (courseIPage == null) throw new RuntimeException("未找到对应科目");
        return courseIPage;
    }

    @Override
    public boolean deleteCourseById(String id) {
        QueryWrapper<Video> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("course_id",id);
        videoService.remove(queryWrapper1);
        List<Video> videoList = videoService.list(queryWrapper1);
        List<String> videoIdList = new ArrayList<>();
        for (Video video : videoList) {
            String videoSourceId = video.getVideoSourceId();
            if (!StringUtils.isEmpty(videoSourceId)) videoIdList.add(videoSourceId);
        }
        ResultEntity resultEntity = vodClient.deleteVideoList(videoIdList);
        if (ResultEntity.FAILED.equals(resultEntity.getResult())) throw new RuntimeException("hystrix....");
        QueryWrapper<Chapter> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("course_id",id);
        chapterService.remove(queryWrapper2);
        return this.removeById(id);
    }

    @Override
    public List<Course> getCourseByTeacherId(String teacherId) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id",teacherId)
                    .orderByDesc("gmt_modified");
        return this.list(queryWrapper);
    }

    @Override
    public CourseInfoVo getCourseInfoById(String id) {
        CourseInfoVo courseInfoVo = baseMapper.selectCourseInfoVoById(id);
        if (courseInfoVo == null) throw new RuntimeException("查询课程信息失败！");
        return courseInfoVo;
    }

    @Override
    public void updatePageViewCount(String id) {
        Course course = this.getById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }
}
